package com.eco.fanliapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.SyUserFootprintMapper;
import com.eco.fanliapp.entity.AppGoods;
import com.eco.fanliapp.entity.SyUserFootprint;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.vo.respone.ResponeResults;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 足迹表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-08-21
 */
@Service
@Slf4j
public class SyUserFootprintServiceImpl extends ServiceImpl<SyUserFootprintMapper, SyUserFootprint> implements ISyUserFootprintService {
    @Autowired
    private ITaoBaoService iTaoBaoService;

    @Autowired
    private SyUserFootprintMapper syUserFootprintMapper;

    @Autowired
    private ITaoBaoMethodService taoBaoMethodService;

    @Autowired
    private IAppGoodsService iAppGoodsService;

    @Autowired
    private RedisLockService redisLockService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 插入足迹
     *
     * @param userId
     * @param itemId
     * @return
     */
    @Override
    public ServerResponse footprintToDo(Long userId, Long itemId) {
        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000 * 5;

        //获取锁
        if (!redisLockService.lock("footprintToDo" + userId + itemId, startTimes + "")) {
            log.info("提现操作频繁，用户Id={}，商品Id={}，记录时间={}", userId, itemId, new Date());
            return ServerResponse.createByErrorMessage("您操作太频繁了，5秒后再试吧");
        }

        SyUserFootprint footprint = syUserFootprintMapper.selectFootPrintById(userId, itemId);
        if (footprint != null) {

            Integer tableId = footprint.getTableId();
            Date belongDate = new Date();
            Date updateTime = new Date();
            int i = syUserFootprintMapper.updateFootPrintById(tableId, belongDate, updateTime);

            if (i > 0) {
                return ServerResponse.createBySuccessMessage("足迹更新成功");
            } else {
                return ServerResponse.createByErrorMessage("足迹更新失败");
            }
        }
        //根据商品id查询商品，获得商品信息
        ServerResponse<ResponeResults> response = iTaoBaoService.getHdkSearchItemIdDetail(itemId.toString(), userId, null, "0",null,null);
        if (response.getStatus() == 200 && response.getData() != null) {
            List<ResponeResults.DataBean> dataBeans = response.getData().getData();
            if (dataBeans != null && dataBeans.size() == 1) {
                for (ResponeResults.DataBean bean : dataBeans
                        ) {
                    SyUserFootprint syUserFootprint = new SyUserFootprint();
                    syUserFootprint.setGoodsId(itemId);
                    syUserFootprint.setUserId(userId);
                    syUserFootprint.setGoodsName(bean.getItemShortTitle());
                    if (bean.getItemShortTitle().isEmpty() || bean.getItemShortTitle().equals("")) {
                        syUserFootprint.setGoodsName(bean.getItemTitle());
                    }
                    syUserFootprint.setGoodsPicture(bean.getItempictUrl());
                    syUserFootprint.setGoodsCoupon(new BigDecimal(bean.getCouponMoney()));
                    syUserFootprint.setGoodsPrice(new BigDecimal(bean.getItemPrice()));
                    syUserFootprint.setGoodsSubsidies(bean.getFanliMoney());
                    syUserFootprint.setGoodsTkPrice(bean.getTheirPriceMoney());
                    syUserFootprint.setBelongDate(new Date());
                    if (bean.getItemType().equalsIgnoreCase("B")) {
                        //2天猫
                        syUserFootprint.setGoodsShopType(2);
                    } else {
                        //1淘宝
                        syUserFootprint.setGoodsShopType(1);
                    }
                    syUserFootprint.setEnable(1);
                    syUserFootprint.setDeleted(0);
                    int i = syUserFootprintMapper.insert(syUserFootprint);

                    if (i > 0) {
                        return ServerResponse.createBySuccessMessage("足迹记录成功");
                    } else {
                        return ServerResponse.createByErrorMessage("足迹记录失败");
                    }
                }
            }

        }
        return ServerResponse.createByErrorMessage("足迹记录失败");
    }

    /**
     * 移除足迹
     *
     * @param userId
     * @param itemId
     * @return
     */
    @Override
    public ServerResponse footprintRemove(Long userId, Long itemId) {
        QueryWrapper<SyUserFootprint> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("goods_id", itemId);
        queryWrapper.eq("enable", 1);
        SyUserFootprint footprint = syUserFootprintMapper.selectOne(queryWrapper);
        if (footprint != null) {
            SyUserFootprint syUserFootprint = new SyUserFootprint();
            syUserFootprint.setTableId(footprint.getTableId());
            syUserFootprint.setDeleted(1);
            syUserFootprint.setUpdateTime(new Date());
            int i = syUserFootprintMapper.updateById(syUserFootprint);

            if (i > 0) {
                return ServerResponse.createBySuccessMessage("足迹删除成功");
            } else {
                return ServerResponse.createByErrorMessage("足迹删除失败");
            }
        }
        return ServerResponse.createByErrorMessage("足迹删除失败");
    }

    /**
     * 足迹列表
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ServerResponse footprintList(Long userId, Long pageNum, Long pageSize) {
        HashMap map = new HashMap();
        //分页
        Page<SyUserFootprint> page = new Page<>(pageNum, pageSize);

        //查询条件
        QueryWrapper<SyUserFootprint> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("belong_date");
        queryWrapper.orderByDesc("create_time");

        IPage<SyUserFootprint> list = syUserFootprintMapper.selectPage(page, queryWrapper);
        if (list != null && list.getRecords().size() > 0) {
            map.put("footprintList", list.getRecords());
            return ServerResponse.createBySuccess("查询成功", map);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多足迹了");
        }

    }

    /**
     * 找相似
     *
     * @param userId
     * @param keyword
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ServerResponse similarList(Long userId, String keyword, Long pageNum, Long pageSize) {
        //标题模糊超级搜索，按照佣金比例
        //按佣金比例倒序
        ResponeResults results = taoBaoMethodService.itemMethon4(keyword, "tk_rate_des ", pageSize, pageNum, userId, null, true, null,"1");

        if (results == null || results.getData() == null || results.getData().size() <= 0) {
            return ServerResponse.createBySuccessCodeMessage(201, "此商品暂无优惠试试其他商品吧~");
        }
        if (results.getData().size() == 1) {
            ResponeResults.DataBean dataBean = results.getData().get(0);
            if ((dataBean.getHasCoupon() && dataBean.getFanliMoney().compareTo(new BigDecimal(0)) > 0)
                    || dataBean.getFanliMoney().compareTo(new BigDecimal(0)) > 0) {

                results = taoBaoMethodService.itemMethon4(keyword, "tk_rate_des ", pageSize, pageNum, userId, null, false, null,"1");
            } else {
                results = taoBaoMethodService.itemMethon4(keyword, "tk_rate_des ", pageSize, pageNum, userId, null, false, null,"1");
                if (results != null && results.getData() != null && results.getData().size() > 0) {
                    for (ResponeResults.DataBean dataBean1 : results.getData()) {
                        if (dataBean.getItemId().equals(dataBean1.getItemId())) {
                            try {
                                results.getData().remove(dataBean1);
                            } catch (Exception e) {

                            }
                        }
                    }
                }
            }
        }
        return ServerResponse.createBySuccess("数据获取成功", results);
    }

    /**
     * 商品点击数
     *
     * @param itemId
     * @return
     */
    @Override
    public ServerResponse appGoodsHitCount(Long itemId) {
        //查询条件

        AppGoods appGoods = iAppGoodsService.selectAppGoodsByIdHitCount(itemId);
        if (appGoods != null && appGoods.getItemid() != null) {
            Integer i = iAppGoodsService.updateAppGoodsByIdHitCount(appGoods.getTableId(), appGoods.getHitCount() + 1);
            if (i > 0) {
                return ServerResponse.createBySuccessMessage("记录成功");
            }
        }
        return null;
    }
}
